<template>
  <div class="app-container">
    <!-- 头部 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="标题"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-input
        v-model="listQuery.author"
        placeholder="作者"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 120px" class="filter-item">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        新增
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="标题">
        <template #default="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="作者" width="110" align="center">
        <template #default="scope">
          {{ scope.row.author }}
        </template>
      </el-table-column>
      <el-table-column label="积分" width="110" align="center">
        <template #default="scope">
          {{ scope.row.points_awarded }}
        </template>
      </el-table-column>
      <el-table-column label="浏览量" width="110" align="center">
        <template #default="scope">
          {{ scope.row.view_count }}
        </template>
      </el-table-column>
      <el-table-column label="排序" width="110" align="center">
        <template #default="scope">
          {{ scope.row.sort_order }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '已发布' : '未发布' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template #default="scope">
          {{ scope.row.create_time }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button v-if="scope.row.status === 0" size="small" type="success" @click="handleModifyStatus(scope.row, 1)">
            发布
          </el-button>
          <el-button v-else size="small" type="info" @click="handleModifyStatus(scope.row, 0)">
            下架
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="listQuery.page"
      v-model:limit="listQuery.limit"
      @pagination="getList"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="dialogFormVisible"
      :title="textMap[dialogStatus]"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleBeforeClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="temp.author" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="temp.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="积分" prop="points_awarded">
          <el-input-number v-model="temp.points_awarded" :min="0" />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="temp.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">已发布</el-radio>
            <el-radio :label="0">未发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getArticles, createArticle, updateArticle, deleteArticle } from '../../api/article'
import Pagination from '../../components/Pagination/index.vue'

export default {
  name: 'ArticleList',
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        title: undefined,
        author: undefined,
        status: undefined
      },
      statusOptions: [
        { label: '已发布', value: 1 },
        { label: '未发布', value: 0 }
      ],
      temp: {
        id: undefined,
        title: '',
        author: '',
        content: '',
        points_awarded: 0,
        sort_order: 0,
        status: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑文章',
        create: '新增文章'
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        points_awarded: [{ required: true, message: '请输入积分', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getArticles(this.listQuery).then(response => {
        if (response.data && response.data.data) {
          this.list = response.data.data
          this.total = response.data.total || 0
        } else {
          this.list = []
          this.total = 0
        }
      }).catch(error => {
        console.error('获取文章列表失败:', error)
        this.list = []
        this.total = 0
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        author: '',
        content: '',
        points_awarded: 0,
        sort_order: 0,
        status: 0
      }
    },
    handleBeforeClose(done) {
      if (this.dialogStatus === 'create' && this.temp.id) {
        done()
        return
      }
      this.$confirm('确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done()
      }).catch(() => {
        // 取消时不关闭弹窗
      })
    },
    handleClose() {
      this.dialogFormVisible = false
    },
    handleCreate() {
      if (this.dialogFormVisible) {
        return
      }
      console.log('开始新增文章')
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      console.log('dialogFormVisible:', this.dialogFormVisible)
      
      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          console.log('表单引用存在')
          this.$refs.dataForm.clearValidate()
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createArticle(this.temp).then((response) => {
            console.log('创建文章响应:', response)
            if (response.data && response.code === 200) {
              const articleData = response.data
              console.log('文章数据:', articleData)
              if (articleData && articleData.id) {
                this.list = [articleData, ...this.list]
                this.$message({
                  type: 'success',
                  message: '创建成功'
                })
                this.dialogFormVisible = false
                this.resetTemp()
                this.getList()
              } else {
                console.error('文章数据格式错误:', articleData)
                this.$message({
                  type: 'error',
                  message: '创建失败：文章数据格式错误'
                })
              }
            } else {
              console.error('响应状态错误:', response.data)
              this.$message({
                type: 'error',
                message: '创建失败：' + (response.data?.msg || '未知错误')
              })
            }
          }).catch(error => {
            console.error('创建文章失败:', error)
            this.$message({
              type: 'error',
              message: error.message || '创建失败'
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateArticle(tempData.id, tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该文章?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArticle(row.id).then(() => {
          const index = this.list.findIndex(v => v.id === row.id)
          this.list.splice(index, 1)
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleModifyStatus(row, status) {
      const text = status === 1 ? '发布' : '下架'
      this.$confirm(`确认${text}该文章?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateArticle(row.id, { status }).then(() => {
          row.status = status
          this.$notify({
            title: '成功',
            message: `${text}成功`,
            type: 'success',
            duration: 2000
          })
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
}
</style> 